package cn.jussi.mvcproject.controller;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet(urlPatterns= {"*.pdo"})
public class ShopController extends HttpServlet{
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		String mn = req.getServletPath();
		mn = mn.substring(1, mn.length()-4);
		try {
			Method method = this.getClass().getDeclaredMethod(mn, HttpServletRequest.class, HttpServletResponse.class);
			method.invoke(this, req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}

	@SuppressWarnings("unused")
	private void shopping(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String pname = req.getParameter("pname");
		req.setAttribute("p", pname);
		req.getRequestDispatcher("/productdetails.jsp").forward(req, resp);
	}
	
	@SuppressWarnings("unused")
	private void addcar(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String pname = req.getParameter("pname");
		//添加购物车
		HttpSession session = req.getSession(true);
		//得到原来购物车的产品
		@SuppressWarnings("unchecked")
		List<String> products = (List<String>)session.getAttribute("car");
		//若购物车没有产品，则创建一个List, 用于存放产品
		if(products==null) {
			products = new ArrayList<>();
		}
		//把本次产品添加到List中
		products.add(pname);
		//把所有产品覆盖到原来的购物车
		session.setAttribute("car", products);	
		resp.sendRedirect(req.getContextPath()+"/shoppingcart.jsp");
	}
}
